<script setup>
definePageMeta({
    title: '库存',
    showInMenu: true, // 控制该页面是否在菜单中显示
    requiresAuth: true, // 控制该页面是否需要登录
    icon: 'icon-steam'
});
const { showLoading, hideLoading } = useLoading()
let dataList = ref([])
let ListTrue = ref([])
// const formFields = [
//     {
//         label: '用户名',
//         type: 'input',
//         model: 'username',
//         placeholder: '请输入用户名',
//         rules: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
//     },
//     {
//         label: '密码',
//         type: 'input',
//         model: 'password',
//         placeholder: '请输入密码',
//         props: { type: 'password' },
//         rules: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
//     },
// ];





const sortState = ref({
    time: null,    // null: 未排序, 'asc': 升序, 'desc': 降序
    price: null,
    wear: null
})

// 排序处理方法
const handleSort = (type) => {
    // 重置其他排序状态
    Object.keys(sortState.value).forEach(key => {
        if (key !== type) sortState.value[key] = null
    })
    // 切换当前排序状态
    if (!sortState.value[type]) {
        sortState.value[type] = 'asc'
    } else if (sortState.value[type] === 'asc') {
        sortState.value[type] = 'desc'
    } else {
        sortState.value[type] = null
    }

    // 根据类型排序
    if (!sortState.value[type]) {
        // 恢复原始顺序
        dataList.value = [...dataList.value]
        return
    }

    // dataList.value.sort((a, b) => {
    //     const isAsc = sortState.value[type] === 'asc'
    //     switch (type) {
    //         case 'time':
    //             return isAsc
    //                 ? new Date(a.createTime) - new Date(b.createTime)
    //                 : new Date(b.createTime) - new Date(a.createTime)
    //         case 'price':
    //             return isAsc
    //                 ? a.purchasePrice - b.purchasePrice
    //                 : b.purchasePrice - a.purchasePrice
    //         case 'wear':
    //             return isAsc
    //                 ? a.abrade - b.abrade
    //                 : b.abrade - a.abrade
    //         default:
    //             return 0
    //     }
    // })
}






const getFacadeColor = (facade) => {
    switch (facade) {
        case '崭新出厂':
            return '#397439';
        case '略有磨损':
            return '#488B48';
        case '久经沙场':
            return '#F1AD4D';
        case '破损不堪':
            return '#D9534F';
        case '战痕累累':
            return '#993A38';
        default:
            return '#FFFFFF';
    }
}


showLoading()
const { data, refresh, error } = await useCustomFetch('/api/steam/queryInventory', {
    method: 'POST',
    withToken: true
})
hideLoading()
if (error.value) {
    $message('接口出错', 'warning')
} else {
    // 将 API 返回的数据复制到 dataList 并添加 `checked` 属性
    if (data.value?.data) {
        dataList.value = data.value.data.map(item => ({
            ...item,
            abrade: Number(0.0703528001904487600),
            checked: false // 初始化 checked 为 false
        }));
    }
}


dataList.value.forEach(item => {
    watch(
        () => item.checked,
        (newValue) => {
            if (newValue) {
                // 添加到 ListTrue
                ListTrue.value.push(item);
            } else {
                // 从 ListTrue 中移除
                ListTrue.value = ListTrue.value.filter(i => i !== item);
            }
        }
    );
});

const StartValuation = async () => {
    if (ListTrue.value.length === 0) {
        $message('请选择饰品', 'warning')
        return
    }

    try {
        const valuationData = ListTrue.value.map(item => ({
            jewelryName: item.jewelryName,
            abrade: item.abrade,
            typeName: '蓝宝石'
        }))
        router.push({
            name: 'order-data',
            params: {
                data: JSON.stringify(valuationData)
            }
        })
    } catch (error) {
        console.log(error, 'error');

    }

}

const refreshInventory = async () => {
    try {
        showLoading()
        // 先调用刷新库存的接口
        await customFetch('/api/steam/refreshInventory', {
            method: 'POST',
            withToken: true
        })
        // 使用 refresh() 刷新数据
        await refresh()
        // 重新处理 data.value 中的数据
        if (data.value?.data) {
            dataList.value = data.value.data.map(item => ({
                ...item,
                abrade: Number(0.0703528001904487600),
                checked: false
            }));
            // 清空已选列表
            ListTrue.value = [];
        }
    } catch (error) {
        console.error('刷新库存失败:', error);
        $message('刷新库存失败', 'error');
    } finally {
        hideLoading()
    }
}

const handleClose = () => {

}

</script>

<template>
    <div class="w-full h-full bg-gray-50 flex flex-col">
        <!-- 搜索表单区域 -->
        <div class="p-6 bg-white shadow-sm">
            <!-- <DynamicForm :fields="formFields" /> -->
        </div>

        <!-- 主体内容区域 - 使用 flex-1 和 flex flex-col 来实现内部布局 -->
        <div class="flex-1 flex flex-col min-h-0"> <!-- min-h-0 确保 flex-1 正常工作 -->
            <div class="p-6 flex flex-col flex-1">
                <!-- 操作栏 -->
                <div class="bg-white p-4 mb-6 rounded-lg shadow-sm flex justify-between items-center flex-wrap gap-4">
                    <div class="flex gap-4">
                        <button @click="handleSort('time')"
                            class="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded-lg flex items-center gap-1"
                            :class="{ 'bg-blue-50': sortState.time }">
                            时间
                            <span v-if="sortState.time" class="text-xs">
                                {{ sortState.time === 'asc' ? '↑' : '↓' }}
                            </span>
                        </button>
                        <button @click="handleSort('price')"
                            class="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded-lg flex items-center gap-1"
                            :class="{ 'bg-blue-50': sortState.price }">
                            价格
                            <span v-if="sortState.price" class="text-xs">
                                {{ sortState.price === 'asc' ? '↑' : '↓' }}
                            </span>
                        </button>
                        <button @click="handleSort('wear')"
                            class="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded-lg flex items-center gap-1"
                            :class="{ 'bg-blue-50': sortState.wear }">
                            磨损
                            <span v-if="sortState.wear" class="text-xs">
                                {{ sortState.wear === 'asc' ? '↑' : '↓' }}
                            </span>
                        </button>
                    </div>
                    <div class="flex gap-4 items-center">
                        <span>已选{{ ListTrue.length }}/{{ dataList.length }}</span>
                        <button @click="StartValuation"
                            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                            开始估价
                        </button>
                        <button @click="refreshInventory"
                            class="px-4 py-2 border border-blue-500 text-blue-500 rounded-lg hover:bg-blue-50">
                            刷新库存
                        </button>
                    </div>
                </div>

                <!-- 商品卡片区域 - 添加 overflow-auto -->
                <div class="flex-1 overflow-auto p-3 custom-scrollbar">
                    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-3">
                        <div v-for="item in dataList" :key="item"
                            class="group relative bg-white rounded-lg shadow-sm hover:shadow-lg transition-all duration-300 cursor-pointer h-[280px]"
                            :class="[item.checked ? 'ring-2 ring-blue-500 bg-blue-50' : '']"
                            @click="item.checked = !item.checked">
                            <!-- 选中标记 -->
                            <div class="absolute -top-2 -right-2 w-4 h-4 rounded-full bg-blue-500 text-white flex items-center justify-center transform scale-0 transition-transform duration-200 z-10"
                                :class="{ 'scale-100': item.checked }">
                                ✓
                            </div>

                            <!-- 标题区域 -->
                            <div class="p-2 border-b">
                                <h3 :title="item.jewelryName" class="truncate text-gray-700 text-sm font-medium">
                                    {{ item.jewelryName }}
                                </h3>
                            </div>

                            <!-- 图片和信息区域 -->
                            <div class="p-2 space-y-2">
                                <!-- 图片容器 -->
                                <div class="relative h-[120px] overflow-hidden rounded-lg">
                                    <img class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                                        src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png"
                                        alt="">
                                    <div
                                        class="absolute left-0 bottom-0 px-1.5 py-0.5 bg-black/50 backdrop-blur-sm text-white text-sm">
                                        磨损: {{ item.abrade }}
                                    </div>
                                    <div :style="{ backgroundColor: getFacadeColor(item.facade) }"
                                        class="absolute left-0 top-0 px-1.5 py-0.5 bg-black/50 backdrop-blur-sm text-white text-sm">
                                        {{ item.facade }}
                                    </div>
                                </div>

                                <!-- 商品信息 -->
                                <div class="space-y-1.5">
                                    <!-- 磨损值进度条 -->
                                    <div class="flex items-center gap-1">
                                        <span class="text-sm text-gray-500">磨损值:</span>
                                        <div class="flex-1 h-2 rounded-full overflow-hidden relative">
                                            <!-- 背景条 -->
                                            <div class="absolute inset-0 flex">
                                                <div class="w-[7%]" style="background-color: rgb(0, 128, 0)"></div>
                                                <div class="w-[8%]" style="background-color: rgb(92, 184, 92)"></div>
                                                <div class="w-[23%]" style="background-color: rgb(240, 173, 78)"></div>
                                                <div class="w-[7%]" style="background-color: rgb(217, 83, 79)"></div>
                                                <div class="flex-1" style="background-color: rgb(153, 58, 56)"></div>
                                            </div>
                                            <!-- 指示器 -->
                                            <div class="absolute top-0 w-1 h-full bg-white border-2 border-gray-700 transform -translate-x-1/2"
                                                :style="{ left: `${Number(item.abrade) * 100}%` }"></div>
                                        </div>
                                        <span class="text-xs text-gray-600 min-w-[60px] text-right">
                                            {{ Number(item.abrade).toFixed(4) }}
                                        </span>
                                    </div>

                                    <!-- 价格信息 -->
                                    <div class="flex items-center justify-between">
                                        <span class="text-sm text-gray-500">价格:</span>
                                        <span class="text-base font-semibold text-blue-600">
                                            ¥{{ item.purchasePrice }}
                                        </span>
                                    </div>

                                    <!-- 其他信息 -->
                                    <div class="flex items-center justify-between text-sm">
                                        <span class="text-gray-500">类型:</span>
                                        <span class="text-gray-700">{{ item.typeName || '-' }}</span>
                                    </div>
                                    <div class="flex items-center justify-between text-sm">
                                        <span class="text-gray-500">品质:</span>
                                        <span class="text-gray-700">{{ item.quality || '-' }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 分页区域 - 固定在底部 -->
            <div class="sticky bottom-0 py-4 bg-white border-t">
                <div class="container mx-auto px-6 flex justify-center">
                    分页
                </div>
            </div>
        </div>
    </div>
</template>


<style lang="scss" scoped>
.aspect-video {
    aspect-ratio: 16 / 9;
}

/* 确保内容区域不会被分页遮挡 */
.grid {
    padding-bottom: 1rem;
}
</style>